package cn.lwj.webService.base;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@SuppressWarnings({ "rawtypes", "unchecked" })
public class BaseManagerImpl implements BaseManager {

	@Resource
	protected JdbcTemplate jdbcTool;

	@Resource(name = "daoTool")
	protected DaoTool daoTool;
	@Resource
	protected CreateNewKey createNewKey;

	//@Resource
	//CommonProperties compro;

	private Logger log = Logger.getLogger(this.getClass());


	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List listFy() throws Exception {
		String sql = "SELECT DM,DMMS FROM BM_FY where DM = 'M00' AND qybz=1 order by DM ASC";
		return jdbcTool.queryForList(sql);
	}

	/**
	 * 通过SQL获取下拉OPTION
	 * 
	 * @param sql
	 *            SQL语句 （DM,DMMS）
	 * @param firstbz
	 *            是否首选
	 * @param value
	 *            默认值
	 * @return
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public String listOptionBySql(String sql, String firstbz, String value)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		if (firstbz.trim().equals("1")) {
			sb.append("<option value=\"\">请选择</option>");
		}
		SqlRowSet rs = jdbcTool.queryForRowSet(sql);
		while (rs.next()) {
			if (rs.getString("C_DM") != null
					&& rs.getString("C_DM").equals(value)) {
				sb.append("<option value=\"" + rs.getString("C_DM")
						+ "\" selected=\"selected\"  >"
						+ rs.getString("C_DMMS") + "</option>");
			} else {
				sb.append("<option value=\"" + rs.getString("C_DM") + "\">"
						+ rs.getString("C_DMMS") + "</option>");
			}
		}
		return sb.toString();
	}


	/**
	 * 通过SQL获取多选下拉OPTION
	 * 
	 * @param sql
	 *            SQL语句 （DM,DMMS）
	 * @param firstbz
	 *            是否首选
	 * @param value
	 *            默认值
	 * @return
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public String listOptionJson(String sql, String firstbz, String value)
			throws Exception {
		JSONArray ja = new JSONArray();
		if (firstbz.trim().equals("1")) {
			JSONObject jo = new JSONObject();
			jo.put("id", "");
			jo.put("text", "请选择");
			jo.put("desc", "");
			ja.add(jo);
		}
		SqlRowSet rs = jdbcTool.queryForRowSet(sql);
		while (rs.next()) {
			if (rs.getString("DM") != null && rs.getString("DM").equals(value)) {
				JSONObject jo = new JSONObject();
				jo.put("id", rs.getString("DM"));
				jo.put("text", rs.getString("DMMS"));
				jo.put("desc", "");
				ja.add(jo);
			} else {
				JSONObject jo = new JSONObject();
				jo.put("id", rs.getString("DM"));
				jo.put("text", rs.getString("DMMS"));
				jo.put("desc", "");
				ja.add(jo);
			}
		}
		return ja.toString();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public Object load(Class<?> clazz, String where) {
		String hql = "from " + clazz.getName();
		if (!where.equals("")) {
			hql = hql
					+ (where.trim().toLowerCase().startsWith("where") ? where
							: " where " + where);
		}
		List list = daoTool.createHQLQuery(hql).list();
		return list != null && list.size() > 0 ? list.get(0) : null;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public Object loadByNoCurrentThread(Class<?> clazz, String where) {
		String hql = "from " + clazz.getName();
		if (!where.equals("")) {
			hql = hql
					+ (where.trim().toLowerCase().startsWith("where") ? where
							: " where " + where);
		}
		List list = daoTool.createHQLQueryListByOpenSeesion(hql);
		return list != null && list.size() > 0 ? list.get(0) : null;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public List findList(Class<?> clazz, String where) {
		String hql = "from " + clazz.getName();
		if (!where.equals("")) {
			if (where.trim().toLowerCase().startsWith("where")) {
				hql = hql + " " + where;
			} else if (where.trim().toLowerCase().startsWith("and")) {
				hql = hql + " where 1=1 " + where;
			} else {
				hql = hql + " where " + where;
			}
		}
		return daoTool.findAll(hql, null);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public List findListByNoCurrentThread(Class<?> clazz, String where) {
		String hql = "from " + clazz.getName();
		if (!where.equals("")) {
			if (where.trim().toLowerCase().startsWith("where")) {
				hql = hql + " " + where;
			} else if (where.trim().toLowerCase().startsWith("and")) {
				hql = hql + " where 1=1 " + where;
			} else {
				hql = hql + " where " + where;
			}
		}
		return daoTool.findAllByOpenSession(hql, null);
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List findList(String hql, Object[] objs) {
		return daoTool.findList(hql, objs);
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List findSQLlist(String sql) throws Exception {
		return jdbcTool.queryForList(sql);
	}

	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
	public void executesql(String sql) throws Exception {
		jdbcTool.execute(sql);
	}



    public String getFyjbm(String fydm) {

        return jdbcTool.queryForObject("SELECT C_DM FROM bm_fy  WHERE C_GFDM='" + fydm + "'", String.class);
    }

    public String getFymc(String fydm, String type) {
        String sql = "";
        try {
            if ("1".equals(type)) {
                sql = "select C_DMMS from BM_FY where C_DM ='" + fydm + "'";
            }else {
                sql = "select C_DMMS from BM_FY where N_GFDM ='" + fydm + "'";
            }
            return jdbcTool.queryForObject(sql, String.class);
        } catch (Exception e) {
            log.error("获取法院名称异常:" + sql);
        }
        return "";
    }


    //组装In条件
    public String getInCondition(Set<String> set)throws Exception {
        StringBuilder sb = new StringBuilder();
        if (set != null && set.size() > 0) {
            for (String bs : set) {
                sb.append(",'" + bs + "'");
            }
            return "("+sb.substring(1)+")";
        }
        return "";
    }

    public String getStr(Object obj) {
        return obj == null || "".equals(obj.toString())|| "undefined".equals(obj.toString())|| "null".equals(obj.toString()) ? "" : obj.toString();
    }
     public String getStr(Object obj,String defaultVal) {
         return obj == null || "".equals(obj.toString())|| "undefined".equals(obj.toString()) || "null".equals(obj.toString()) ? defaultVal : obj.toString();
    }
    public Integer getInt(Object obj) {
        return obj == null || "".equals(obj.toString())|| "undefined".equals(obj.toString()) || "null".equals(obj.toString()) ? 0 : Integer.parseInt(obj.toString());
    }
    public Integer getInt(Object obj, Integer defaultVal) {
        return obj == null || "".equals(obj.toString())|| "undefined".equals(obj.toString())|| "null".equals(obj.toString())  ? defaultVal : Integer.parseInt(obj.toString());
    }
    public Double getDouble(Object obj) {
        return obj == null || "".equals(obj.toString())|| "undefined".equals(obj.toString()) || "null".equals(obj.toString()) ? 0 : Double.parseDouble(obj.toString());
    }

	public String getMapValue(Map m, String key, String dv){
		if (m==null){
			return dv;
		}
		return (m.get(key)==null||m.get(key).toString().trim().equals("null")||m.get(key)=="")?dv:m.get(key).toString();
	}

    /**
     * 根据延期许可id获取当前批次案件
     * @param cYqxkId
     * @return
     */
    public String getYqxkGlaj(String cYqxkId) {
        StringBuilder jzbIds = new StringBuilder();
        String sql = "SELECT C_JZB_ID FROM `t_xf_yqxk_ajxx` WHERE C_YQXK_ID ='" + cYqxkId + "'";
        try {
            List<Map<String, Object>> list = jdbcTool.queryForList(sql);
            if (list != null && list.size() > 0) {
                for (Map<String, Object> e : list) {
                    jzbIds.append("," + getStr(e.get("C_JZB_ID")));
                }
            }else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jzbIds.substring(1);
    }
    /**
     * 根据正则表达式得到匹配内容  只有一次的情况
     * @param regEx
     * @param qss
     * @return
     */
    public String getContent(String regEx, String qss) {
        String content = "";
        Matcher m = Pattern.compile(regEx).matcher(qss);
        if (m.find()) {
            content = m.group();
        }
        return content;
    }
    //组装mysql--in条件
    public String formatInCondition(String condition) {
        if (condition == null || "".equals(condition)) return "";
        String[] conditionAry = condition.split(",");
        StringBuilder sb = new StringBuilder();
        if (conditionAry.length > 0) {
            for (String c : conditionAry) {
                sb.append("," + "\'" + c + "\'");
            }
            return sb.substring(1);
        }
        return "";
    }
}
